import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'order_list_entity.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_yres/tool/AppSaveInfoUtil.dart';
import 'package:flutter_yres/tool/constant.dart';


class AllOrderPage extends StatefulWidget {
  var type;
  AllOrderPage({Key key, @required this.type}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return AllOrderView();
  }
}

class AllOrderView extends State<AllOrderPage>
    with AutomaticKeepAliveClientMixin, WidgetsBindingObserver {
  List<OrderListDataData> dataList = List();
  int page = 1;
  EasyRefreshController _controller = new EasyRefreshController();
  String token = "";
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    getString(TOKEN).then((value) {
      token = value;
      if (token == null) {
        return;
      }
      loadList();
    });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // TODO: implement didChangeAppLifecycleState
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed)
      getString(TOKEN).then((value) {
        token = value;
      });
  }

  loadList() async {
    Map map = new Map();
    map['token'] = token;
    map['status'] = widget.type;
    map['p'] = page;
    map['per'] = 10;
    // map['sign_type'] = SignType.USER_ORDER_LIST;
    FormData data= FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response =
        await HttpUtil().post(Api.VipOrderListUrl, data: data);
    Map userMap = json.decode(response.data);
    print('订单');
    print(userMap);
    if (userMap['code'] != 1) {
      Fluttertoast.showToast(msg: userMap['msg']);
      return;
    }
    OrderListEntity homeListEntity = new OrderListEntity.fromJson(userMap);
    if (mounted)
      setState(() {
        if (page == 1) {
          dataList.clear();
          dataList.addAll(homeListEntity.data);
        } else {
          dataList.addAll(homeListEntity.data);
        }
        if (page == 1) {
          _controller.resetLoadState();
          _controller.finishRefresh();
        } else {
          _controller.finishLoad(noMore: homeListEntity.data.length == 0);
          if (homeListEntity.data.length == 0) {
            Fluttertoast.showToast(msg: "暂无更多数据");
          }
        }
      });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    // TODO: implement build
    return new Container(
      child: new Container(
        color: divideColor,
        child: new EasyRefresh(
          controller: _controller,
          header: MaterialHeader(),
          footer: MaterialFooter(),
          enableControlFinishLoad: true,
          enableControlFinishRefresh: true,
          child: ListView.separated(
              itemBuilder: _renderRow,
              separatorBuilder: (BuildContext context, int index) {
                return Container(
                  color: divideColor,
                  height: 10,
                );
              },
              itemCount: dataList == null ? 0 : dataList.length),
          onRefresh: () async {
            page = 1;
            loadList();
          },
          onLoad: () async {
            page++;
            loadList();
          },
        ),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    return new GestureDetector(
      onTap: () {
        // Navigator.of(context).push(MaterialPageRoute(builder: (context) {
        //   return new OrderDetailPage(
        //     id: dataList[index].id,
        //   );
        // }));
      },
      child: new Container(
        decoration: BoxDecoration(
            color: Colors.white, borderRadius: BorderRadius.circular(0.0)),
        padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Row(
              children: <Widget>[
                Expanded(
                  child: Text("订单号: " + dataList[index].order_num,
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE))),
                ),
                Text(
                    dataList[index].status == "1"
                        ? '待审核'
                        : dataList[index].status == "2"
                            ? "待发货"
                            : dataList[index].status == "3" ? "待收货" : "已完成",
                    style: TextStyle(
                        color: mainColor,
                        fontSize:
                            ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE)))
              ],
            ),
            Container(
              height: 10,
            ),
            // ListView.builder(
            //   padding: EdgeInsets.all(0),
            //   physics: new NeverScrollableScrollPhysics(),
            //   itemBuilder: (BuildContext context, int index1) {
            //     return Container(
            //       child: Row(
            //         children: <Widget>[
            //           ClipRRect(
            //             borderRadius: BorderRadius.circular(2),
            //             child: Image.network(
            //                 Api.BaseUrl + dataList[index].datas[index1].img,
            //                 width: ScreenUtil.getInstance().setHeight(DP_120),
            //                 fit: BoxFit.fill,
            //                 height: ScreenUtil.getInstance().setHeight(DP_120)),
            //           ),
            //           Container(
            //             width: 10,
            //           ),
            //           Column(
            //             crossAxisAlignment: CrossAxisAlignment.start,
            //             children: <Widget>[
            //               Text(dataList[index].datas[index1].goods_name,
            //                   maxLines: 2,
            //                   overflow: TextOverflow.ellipsis,
            //                   style: TextStyle(
            //                       fontSize: ScreenUtil.getInstance()
            //                           .setSp(NORMAL_FONT_SIZE))),
            //               Container(
            //                 height: 4,
            //               ),
            //               Container(
            //                 width: (MediaQuery.of(context).size.width -
            //                     ScreenUtil.getInstance().setHeight(DP_180)),
            //                 child: Html(
            //                     data: "规格: " +
            //                         dataList[index].datas[index1].sku_str,
            //                     defaultTextStyle: TextStyle(
            //                         color: Colors.black45,
            //                         fontSize: ScreenUtil.getInstance()
            //                             .setSp(SMALL_FONT_SIZE))),
            //               ),
            //               Container(
            //                 height: 6,
            //               ),
            //               Row(
            //                 children: <Widget>[
            //                   Text("¥" + dataList[index].datas[index1].price,
            //                       style: TextStyle(
            //                           color: mainColor,
            //                           fontSize: ScreenUtil.getInstance()
            //                               .setSp(NORMAL_FONT_SIZE))),
            //                   Container(
            //                     width: (MediaQuery.of(context).size.width -
            //                         ScreenUtil.getInstance().setHeight(DP_300)),
            //                   ),
            //                   Text("X" + dataList[index].datas[index1].num,
            //                       style: TextStyle(
            //                           color: black_99,
            //                           fontSize: ScreenUtil.getInstance()
            //                               .setSp(SMALL_FONT_SIZE))),
            //                 ],
            //               )
            //             ],
            //           )
            //         ],
            //       ),
            //     );
            //   },
            //   itemCount: dataList[index].datas.length,
            //   shrinkWrap: true,
            // ),
            Container(
              height: 10,
            ),
            Text(
                "收货人: " +
                    (dataList[index].consignee!=null?dataList[index].consignee.toString():'') +
                    "   " +
                    (dataList[index].contact_number!=null?dataList[index].contact_number.toString():''),
                style: TextStyle(
                    color: black_99,
                    fontSize: ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE))),
            Container(
              height: 10,
            ),
            Text(
                "物流: " +(dataList[index].logistics!=null?dataList[index].logistics.toString():'') +
                    "   " +
                    (dataList[index].express_number!=null?dataList[index].express_number.toString():''),
                style: TextStyle(
                    color: black_99,
                    fontSize: ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE))),
            Container(
              width: double.infinity,
              alignment: Alignment.centerRight,
              child: Text("实际付款: " + dataList[index].allprice,
                  style: TextStyle(
                      color: black,
                      fontSize:
                          ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE))),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: <Widget>[
                Offstage(
                  offstage: dataList[index].status != "1",
                  child: GestureDetector(
                    child: Container(
                      padding: EdgeInsets.fromLTRB(10, 2, 10, 2),
                      decoration: BoxDecoration(
                          border: Border.all(color: black_99, width: 1),
                          borderRadius: BorderRadius.circular(30)),
                      child: Text('取消订单',
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE),
                              color: black_99)),
                    ),
                    onTap: () {
                      showDialog(
                        context: context,
                        builder: (context) => new AlertDialog(
                          title: new Text('提示'),
                          content: new Text('确定取消该条订单吗，取消后不可撤回'),
                          actions: <Widget>[
                            new FlatButton(
                              onPressed: () => Navigator.of(context).pop(false),
                              child: new Text(
                                '取消',
                                style: TextStyle(color: Colors.grey),
                              ),
                            ),
                            new FlatButton(
                              onPressed: () {
                                Navigator.of(context).pop(false);
                                cancle(index);
                              },
                              child: new Text('确定取消',
                                  style: TextStyle(color: mainColor)),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
                ),
                  Offstage(
                  offstage: dataList[index].status != "3",
                  child: GestureDetector(
                    child: Container(
                      margin: EdgeInsets.only(right: 10),
                      padding: EdgeInsets.fromLTRB(10, 2, 10, 2),
                      decoration: BoxDecoration(
                          border: Border.all(color: mainColor, width: 1),
                          borderRadius: BorderRadius.circular(30)),
                      child: Text('查看物流',
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE),
                              color: mainColor)),
                    ),
                    onTap: () {
                      Fluttertoast.showToast(msg: "敬请期待");
                    },
                  ),
                ),
                Offstage(
                  offstage: dataList[index].status != "3",
                  child: GestureDetector(
                    child: Container(
                      padding: EdgeInsets.fromLTRB(10, 2, 10, 2),
                      decoration: BoxDecoration(
                        color: mainColor,
                          border: Border.all(color: mainColor, width: 1),
                          borderRadius: BorderRadius.circular(30)),
                      child: Text('确认收货',
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE),
                              color: white)),
                    ),
                    onTap: () {
                      showDialog(
                        context: context,
                        builder: (context) => new AlertDialog(
                          title: new Text('提示'),
                          content: new Text('确定已经收到货物吗,确认后不可撤回'),
                          actions: <Widget>[
                            new FlatButton(
                              onPressed: () => Navigator.of(context).pop(false),
                              child: new Text(
                                '取消',
                                style: TextStyle(color: Colors.grey),
                              ),
                            ),
                            new FlatButton(
                              onPressed: () {
                                Navigator.of(context).pop(false);
                                confirm(index);
                              },
                              child: new Text('确定',
                                  style: TextStyle(color: mainColor)),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }

  // del(id) async {
  //   FormData formData = new FormData.fromMap({
  //     "token": token,
  //     "order_id": id,
  //   });
  //   Response<String> response =
  //       await HttpUtil().post(Api.VipOrderCancelMsgUrl, data: formData);
  //   Map userMap = json.decode(response.data);
  //   int code = userMap["code"];
  //   String msg = userMap["msg"];
  //   Navigator.of(context).pop(1);
  //   Fluttertoast.showToast(msg: msg);
  //   if (code == 0) {
  //     page = 1;
  //     loadList();
  //   }
  //   return true;
  // }

  confirm(int index) async {
    // Map map = new Map();
    // map['token'] = token;
    // map['order_id'] = dataList[index].id;
    // // map['sign_type'] = SignType.CONFIRM_ORDER;
    // Response<String> response =
    //     await HttpUtil().post(Api.CONFIRM_ORDER, data: getSign(map));
    // Map userMap = json.decode(response.data);
    // int code = userMap["code"];
    // String msg = userMap["msg"];
    // Fluttertoast.showToast(msg: msg);
    // if (code == 1 && mounted) {
    //   dataList.removeAt(index);
    //   setState(() {});
    // }
    // return true;
  }

  cancle(int index) async {
    FormData formData = new FormData.fromMap({
      "token": token,
      "order_id": dataList[index].id,
    });
    // map['sign_type'] = SignType.CANCLE_ORDER;
    Response<String> response =
        await HttpUtil().post(Api.VipOrderCancelMsgUrl, data: formData);
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Fluttertoast.showToast(msg: msg);
    if (code == 1 && mounted) {
      dataList.removeAt(index);
      setState(() {});
    }
    return true;
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
